package com.yhcnet.blog.controller;


import com.yhcnet.blog.reponse.IMG;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin
@ResponseBody
public class ImgController {

    @RequestMapping("/test")
    @ResponseBody
    @CrossOrigin
    public IMG imgload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "editormd-image-file", required = true) MultipartFile multipartFile) throws IOException, NoSuchAlgorithmException {


        if(multipartFile.isEmpty()){
            IMG img = new IMG();
            img.setMessage("upload fail");
            img.setSuccess(1);
            return img;
        }
//        获取文件名
        String filename = multipartFile.getOriginalFilename();//全名
        String firstName=filename.substring(0,filename.lastIndexOf(".")); //文件名
        String lastName = filename.substring(firstName.length());//拓展名

//       获取一个时间戳
        String finaName = UUID.randomUUID().toString();

//      创建一个新文件
        File file = new File("img");
        String canonicalPath = file.getCanonicalPath();

        if(!file.isDirectory()) file.mkdir();
        multipartFile.transferTo(Paths.get(canonicalPath+"/img"  + finaName + lastName));

//        System.out.println("now"+canonicalPath);
//        System.out.println(Paths.get(canonicalPath+"/img"  + finaName + lastName));
//        System.out.println(Paths.get("http:/"+"/jysx.xyz/img/img"  + finaName + lastName).toString());
//        System.out.println("http://jysx.xyz"+Paths.get("/img/img"  + finaName + lastName).toString());
        //返回值
        IMG img = new IMG();
        img.setMessage("upload success");
        img.setSuccess(1);
        img.setUrl("http://jysx.xyz"+Paths.get("/img/img"  + finaName + lastName).toString());
        return img;
    }
}
